package com.zhenwgang.listen_books.servlet.track;

import com.zhenwgang.listen_books.repository.TrackRepo;
import com.zhenwgang.listen_books.util.Log;
import com.zhenwgang.listen_books.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 音乐上传动态资源
 * @author Violet
 * @date 2022/07/09 14:54
 **/

@WebServlet("/studio/track/upload.do")
@MultipartConfig
public class UploadDoServlet extends HttpServlet {
    private static final TrackRepo trackRepo = new TrackRepo();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserVO userVO = null;
        HttpSession session = req.getSession(false);
        if (session != null){
            userVO = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter write = resp.getWriter();

        if (userVO == null){
            write.println("用户未登录");
            return;
        }

        Log.println("登录用户为: " + userVO);

        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        Log.println("获取到的 title 是 " + title);

        Part track = req.getPart("track");
        String type = track.getContentType();
        Log.println("上传的type为：" + type);
        InputStream contentInputStream = track.getInputStream();

        trackRepo.insert(userVO.uid, title, type, contentInputStream);
        Log.println("上传成功");

        write.println("上传成功");
    }
}